#array javascript
Explore tagged Tumblr posts
Text
Had a moment of listening to music I liked back when I was a teenager (& still like) and having a whole. Realization . That I like myself as I am now sooooo much better than I like teenage me. And I started thinking about Why.
There's a lot to it I'm pretty sure, & most of it centers around the fact that I just... didn't really know who I was as a person. I didn't really have hobbies outside of what I did in school (aka orchestra) and like. Video games + anime. I did creative writing in middle school, but dropped off in high school for... some reason? I still made original characters and played around with them a lot, but it was mostly just in drawing and thinking about them. I never actually *wrote*, and I in fact didn't get back into creative writing at all until I was 23 years old. I was someone who had spent so long hiding behind others and just doing what I was told that I just... didn't have any real direction. I didn't know what I even *wanted*. I thought I knew, but in hindsight, I can confidently say that I didn't. I was just an insecure teen drifting through life and not thinking about things beyond what was immediately in front of me. Which is pretty standard for teenagers I guess, but not all of them. Not at all.
Compared to now, where I have Many hobbies, most notably being writing. As I am now, I am just Intrinsically a writer. And it's weird to remember that I wasn't even really *writing* before 5 years ago (besides text rps, which did a lot for developing my writing skill! But still aren't a replacement for writing individually). As a teen, I wasnt into dnd, I was incredibly out of shape, & I was a lot less aggressive and focused. I was the type to avoid sports!!! I hated them!!!! But as I am now, I Love biking and can easily bike for an hour+ no problem (I remember being a teen and trying to go on just 10 minute bike rides in the summer and just *dying* from it), & I love working out. I wanna be strong!!! I LOVE being strong!!! And I was an absolute mess with things like public speaking & working in groups, vs now where I can do an impromptu presentation no problem & I'm often the unofficial leader in group projects bc im typically the one who does the organizing and allotments of work. A side effect of working as a supervisor and then assistant manager for so long. I have a lot more confidence in my perceptions and judgements, & I have the self-assurance to assert these things. And this is only really the tip of the iceberg with all the differences.
I just feel like an entirely different person, almost. The cores are the same, or at least damn near similar, with the things I want out of life & the sorts of things I enjoy, but it's like. The difference between finding a random rock off the side of the road & then that rock when it's been sanded and carved and decorated to be something individual and unique. You look at them side by side and it's something dull vs something shiny and intricate. The origins can't be ignored and dismissed, & I certainly would never resent younger me for just doing the best with what I knew at the time. But it's just astounding how much difference time and experience will have for growing and developing as a person. Things I consider integral to my personhood weren't even thoughts in my mind back then. We are almost entirely different people.
#speculation nation#under readmore bc I just got contemplative. not negative really either.#ultimately it's that kind of thing of like. college & all my experiences within it have done a LOT for developing who i am as a person.#i wouldnt be nearly so comfortable with public speaking if it werent for how many speech classes ive taken over the years.#but it's also the fact that i was working to figure out who i was during college that made me fumble it so hard.#i wanted to be an engineer. can you believe it? i was so CERTAIN of it as a teenager. but it was only really bc of the family i have/had#that are/were engineers. i didnt have personal interest in it. it was just the Thing To Do.#so i got to college and i *hated* it and i had to take several years to figure out what i actually Wanted.#i realized pretty quickly that i wanted to focus on computers after my first coding class. but thats so BROAD#and computer science wasnt for me either. i fucking hated computer science. but computer information & technology??#this is my shit. and honestly it's so weird to remember that just 10 years i knew very little about computers#and now ill be sitting in my web programming class & theyre talking about javascript and loops and such within it#and im just zoning tf out bc Yeah Yeah do while loops ive heard it a million times before. arrays?? yeah whatever i got it#but back in 2016 i had to learn these things for the first time!!! it was entirely new to me!!! teenage me didnt KNOW#so me being a computer person with a specialization in business and hobbies of writing and biking and dnd. i had NONE of those things!!!#i didnt even collect knives!!!!! granted thats mostly bc i Couldnt buy many of them yet + i also didnt have much money lol#bc i never even worked a job until i got to college. that's also unimaginable to me. imagine not knowing what it's like to Work...#i remember getting $500 or so in graduation gifts after graduating high school & my mind was just Blown#had never had that much money before. it was crazy to me. meanwhile with a job paying every other week $500 was a *low* paycheck.#but i also have to pay bills and rent and buy food and all this stuff. also things i didnt have to worry about back then. ALSO weird.#idk theres a lotta bullshit i gotta deal with as an adult but i like who i am now so much better. feel so much more *myself*#than just a directionless teenager waiting for someone to tell them what to do.#it's amazing what 10 years will do for your development as a person. absolutely wild.
2 notes
·
View notes
Text
Coding is funny as fuck (while ur not doing it.) i was trying to get something to work and it had been like an hour+ before i tried something else, longhand. (But simple way, so I still kiiinda saved some time?)
Ed was in the room w me and hearing me bitch and cuss and plead to the fucking computer, occasionally injecting jokes in my miserable fit.
I figured out what it was, faced ed, sneered and put my head in my hands. Told them, “I figured out the answer.”
Ed waited for me to continue, because what the fuck does that mean when u dont code.
Then, I said: “I don’t like the answer.”
#i had to convert an array of numbers#pulled fucking ASYNC STYLE#into an array of strings. dynamically.#the array had a length of 702.#and its length will increase in the future.#working async w an array of objects#and doing shit w the array#w/o losing sync along the way#is pretty new shit to me.#thankfully i knew i just had to map the thing somehow.#javascript#jquery
3 notes
·
View notes
Text
So, a single method call to flatMap is consistently slower than two method calls, to filter, and then map? The difference persists on smaller arrays (meaning, before the JIT compiler kicks in), see the last picture for an array of length 100. Not what I expected.
I guess, the lessons here are "don't be clever" and "avoid premature optimization".
#codeblr#javascript#got inspired by the latest video on fireship's side channel#wrote similar obscure flatMap nonsense instead of a straightforward filter & map combo a few days ago#naively thinking it would be more efficient to iterate over an array once instead of twice#“woll it wosn't”
6 notes
·
View notes
Text
Normally I just post about movies but I'm a software engineer by trade so I've got opinions on programming too.
Apparently it's a month of code or something because my dash is filled with people trying to learn Python. And that's great, because Python is a good language with a lot of support and job opportunities. I've just got some scattered thoughts that I thought I'd write down.
Python abstracts a number of useful concepts. It makes it easier to use, but it also means that if you don't understand the concepts then things might go wrong in ways you didn't expect. Memory management and pointer logic is so damn annoying, but you need to understand them. I learned these concepts by learning C++, hopefully there's an easier way these days.
Data structures and algorithms are the bread and butter of any real work (and they're pretty much all that come up in interviews) and they're language agnostic. If you don't know how to traverse a linked list, how to use recursion, what a hash map is for, etc. then you don't really know how to program. You'll pretty much never need to implement any of them from scratch, but you should know when to use them; think of them like building blocks in a Lego set.
Learning a new language is a hell of a lot easier after your first one. Going from Python to Java is mostly just syntax differences. Even "harder" languages like C++ mostly just mean more boilerplate while doing the same things. Learning a new spoken language in is hard, but learning a new programming language is generally closer to learning some new slang or a new accent. Lists in Python are called Vectors in C++, just like how french fries are called chips in London. If you know all the underlying concepts that are common to most programming languages then it's not a huge jump to a new one, at least if you're only doing all the most common stuff. (You will get tripped up by some of the minor differences though. Popping an item off of a stack in Python returns the element, but in Java it returns nothing. You have to read it with Top first. Definitely had a program fail due to that issue).
The above is not true for new paradigms. Python, C++ and Java are all iterative languages. You move to something functional like Haskell and you need a completely different way of thinking. Javascript (not in any way related to Java) has callbacks and I still don't quite have a good handle on them. Hardware languages like VHDL are all synchronous; every line of code in a program runs at the same time! That's a new way of thinking.
Python is stereotyped as a scripting language good only for glue programming or prototypes. It's excellent at those, but I've worked at a number of (successful) startups that all were Python on the backend. Python is robust enough and fast enough to be used for basically anything at this point, except maybe for embedded programming. If you do need the fastest speed possible then you can still drop in some raw C++ for the places you need it (one place I worked at had one very important piece of code in C++ because even milliseconds mattered there, but everything else was Python). The speed differences between Python and C++ are so much smaller these days that you only need them at the scale of the really big companies. It makes sense for Google to use C++ (and they use their own version of it to boot), but any company with less than 100 engineers is probably better off with Python in almost all cases. Honestly thought the best programming language is the one you like, and the one that you're good at.
Design patterns mostly don't matter. They really were only created to make up for language failures of C++; in the original design patterns book 17 of the 23 patterns were just core features of other contemporary languages like LISP. C++ was just really popular while also being kinda bad, so they were necessary. I don't think I've ever once thought about consciously using a design pattern since even before I graduated. Object oriented design is mostly in the same place. You'll use classes because it's a useful way to structure things but multiple inheritance and polymorphism and all the other terms you've learned really don't come into play too often and when they do you use the simplest possible form of them. Code should be simple and easy to understand so make it as simple as possible. As far as inheritance the most I'm willing to do is to have a class with abstract functions (i.e. classes where some functions are empty but are expected to be filled out by the child class) but even then there are usually good alternatives to this.
Related to the above: simple is best. Simple is elegant. If you solve a problem with 4000 lines of code using a bunch of esoteric data structures and language quirks, but someone else did it in 10 then I'll pick the 10. On the other hand a one liner function that requires a lot of unpacking, like a Python function with a bunch of nested lambdas, might be easier to read if you split it up a bit more. Time to read and understand the code is the most important metric, more important than runtime or memory use. You can optimize for the other two later if you have to, but simple has to prevail for the first pass otherwise it's going to be hard for other people to understand. In fact, it'll be hard for you to understand too when you come back to it 3 months later without any context.
Note that I've cut a few things for simplicity. For example: VHDL doesn't quite require every line to run at the same time, but it's still a major paradigm of the language that isn't present in most other languages.
Ok that was a lot to read. I guess I have more to say about programming than I thought. But the core ideas are: Python is pretty good, other languages don't need to be scary, learn your data structures and algorithms and above all keep your code simple and clean.
#programming#python#software engineering#java#java programming#c++#javascript#haskell#VHDL#hardware programming#embedded programming#month of code#design patterns#common lisp#google#data structures#algorithms#hash table#recursion#array#lists#vectors#vector#list#arrays#object oriented programming#functional programming#iterative programming#callbacks
20 notes
·
View notes
Text
Shelly Scripting – JavaScript-Grundlagen für Einsteiger: Arrays verstehen und anwenden
Arrays sind eine der einfachsten Möglichkeiten, mehrere Werte wie Zahlen oder Zeichenketten in einer Art Liste zu speichern. Jeder Eintrag hat dabei eine feste Position und kann über einen sogenannten Index angesprochen werden. Besonders praktisch ist das Zusammenspiel mit Schleifen: Damit lassen sich alle Elemente eines Arrays effizient durchlaufen – zum Beispiel, um sie auszugeben oder zu bearbeiten. In diesem Beitrag zeige ich dir, wie Arrays aufgebaut sind und wie du sie sinnvoll nutzen kannst. https://youtu.be/TRULc___5ps 📌 Tipp: Eine ausführliche Einführung in JavaScript-Grundlagen wie Variablen, Bedingungen und die verschiedenen Schleifenarten findest du in meinem Blogbeitrag:👉 Shelly Scripting – JavaScript-Grundlagen für Einsteiger: Variablen, Bedingungen & Logik verstehen 🎥 Zusätzlich gibt’s auf meinem YouTube-Kanal eine eigene Playlist, in der ich alle Themen Schritt für Schritt in einzelnen Videos erkläre. Was ist ein Array? Ein Array ist eine geordnete Sammlung von Werten, die unter einem gemeinsamen Namen gespeichert werden. Man kann sich ein Array wie eine Liste oder ein Regal mit nummerierten Fächern vorstellen – in jedem Fach liegt ein Wert. Diese Werte können zum Beispiel Zahlen oder Zeichenketten sein. Wichtig:Die Zählung (der sogenannte Index) beginnt bei 0, nicht bei 1! Das bedeutet: - Das erste Element eines Arrays hat den Index 0 - Das zweite Element den Index 1 - Und so weiter … Beispiel: Gemüse-Array let gemuese = ; In diesem Array haben wir vier Gemüsesorten gespeichert. Die Zuordnung sieht so aus: IndexWert0"Tomate"1"Gurke"2"Paprika"3"Karotte" Wenn du z. B. auf das erste Element zugreifen möchtest, schreibst du: print(gemuese); // Ausgabe: Tomate Und so greifst du auf das letzte Element zu: print(gemuese); // Ausgabe: Karotte Shelly Scripting - Arrays - Ausgabe von Werten aus dem Array Zugriff auf nicht vorhandene Elemente Wenn du in einem Array einen Index auswählst, für den kein Wert existiert, bekommst du als Ergebnis den speziellen Wert undefined. Das bedeutet, dass an dieser Stelle nichts gespeichert ist. Schauen wir uns das am Beispiel an: // IDX 0 IDX 1 IDX 2 IDX 3 let gemuese = ; print(gemuese); // Ausgabe: undefined In unserem Array sind nur vier Elemente enthalten, mit den Indizes 0 bis 3. Wenn du versuchst, auf gemuese zuzugreifen, also auf den fünften Platz, bekommst du undefined, weil dort kein Wert hinterlegt ist. 🔎 Tipp:Vor dem Zugriff kannst du mit einer Bedingung prüfen, ob der Index gültig ist: if (gemuese !== undefined) { print(gemuese); } else { print("An dieser Stelle gibt es kein Gemüse!"); } Shelly Scripting - Arrays - Zugriff auf nicht vorhandenen Index Die Länge eines Arrays mit length ermitteln Mit der Eigenschaft length kannst du herausfinden, wie viele Elemente sich aktuell in einem Array befinden. let gemuese = ; print("Anzahl der Elemente im Array: "+ gemuese.length); Shelly Scripting - Arrays - ermitteln der Anzahl der Elemente Das bedeutet: Unser gemuese-Array enthält vier Elemente.Aber Achtung: Der letzte gültige Index ist nicht 4, sondern 3, denn die Zählung beginnt wie immer bei 0. 👉 Merke:Die length-Eigenschaft gibt dir die Anzahl der Elemente, nicht den höchsten Index. Der höchste Index ist also immer length - 1. Beispiel für Zugriff mit length let gemuese = ; let letztesGemuese = gemuese; print(letztesGemuese); // Ausgabe: Karotte So kannst du dynamisch auf das letzte Element zugreifen, egal wie viele Werte im Array gespeichert sind. Array mit einer for-Schleife durchlaufen Eine der häufigsten Methoden, um alle Werte eines Arrays zu verarbeiten oder auszugeben, ist die for-Schleife. Sie ermöglicht es dir, nacheinander auf jeden Index des Arrays zuzugreifen. Hier ein Beispiel mit unserem Gemüse-Array: let gemuese = ; for (let index = 0; index < gemuese.length; index++) { print(gemuese); } Shelly Scripting - Arrays - Ausgabe der Elemente mit einer ForSchleife 🔍 Was passiert hier? - Die Schleife beginnt bei index = 0 (also dem ersten Element). - Sie läuft so lange, wie der Index kleiner als gemuese.length ist. - Mit gemuese greifen wir auf das jeweilige Element zu. - Die Funktion print() gibt das Element aus (alternativ in der Konsole: console.log()). 💡 Wichtig:Wir verwenden index < gemuese.length – nicht - Die Methode - Sie übergibt jedes Element nacheinander an die anonyme Funktion - Die Funktion wird print(element)); Wann forEach() verwenden? ✅ Vorteile: - Weniger Fehleranfällig (kein manuelles Zählen oder Indexvergleich) - Lesbarer und kürzerer Code - Perfekt für einfache Ausgaben oder Operationen auf jedem Element ⚠️ Beachte:forEach() ist nicht abbrechbar – ein break oder return beendet nicht die gesamte Schleife wie bei for. Für Fälle mit Abbruchbedingung bleibt for oft die bessere Wahl. Mehrdimensionale Arrays – Strukturen im Array Mit einem mehrdimensionalen Array kannst du komplexere Datenstrukturen abbilden. Statt nur einer Liste mit Werten speicherst du darin Arrays innerhalb von Arrays – ähnlich wie bei einer Tabelle oder Matrix. Das eignet sich besonders gut, wenn du Daten gruppieren möchtest – z. B. mehrere Räume in einer Wohnung, jeweils mit verschiedenen smarten Geräten. let wohnung = , , ], , , ] ]; for (let i = 0; i < wohnung.length; i++) { print("Raum: " + wohnung); for (let j = 1; j < wohnung.length; j++) { let gruppe = wohnung; print(" Gruppe: " + gruppe); for (let k = 1; k < gruppe.length; k++) { print(" Gerät: " + gruppe); } } } Hinweis: Da die Console lediglich die letzten 10 Einträge anzeigt, habe ich hier zu jsfiddle.net gewechselt. Zusätzlich habe ich für die kompatibilität die Funktion print implementiert, somit kann man den Code 1:1 übernehmen. Shelly Scripting - Arrays - Mehrdimensionale Arrays - Ausgabe Werte in einem Array ersetzen Ein Array ist veränderbar – du kannst also einzelne Werte gezielt austauschen, indem du einen neuen Wert an einer bestimmten Stelle (Index) zuweist. Beispiel: let gemuese = ; gemuese = "Kohlrabi"; ➡️ Was passiert hier?Das Element mit dem Index 2 (also der dritte Eintrag: "Paprika") wird durch "Kohlrabi" ersetzt. Shelly Scripting - Arrays - Ersetzen von Elementen 💡 So kannst du gezielt Werte anpassen – etwa, wenn sich ein Sensorwert ändert oder ein Gerät ausgetauscht wurde. Werte per Index hinzufügen Wie gezeigt, kannst du mit gemuese = "Kohlrabi" einen bestehenden Eintrag ersetzen.Doch was passiert, wenn du einen Index verwendest, der noch nicht existiert? Beispiel: let gemuese = ; gemuese = "Brokkoli"; ➡️ Ergebnis:Der Eintrag "Brokkoli" wird an Position 4 eingefügt – das Array wächst automatisch. Shelly Scripting - Arrays - Hinzufügen von Elementen ⚠️ Achtung:Wenn du z. B. gemuese = "Spinat" schreibst, aber Index 5 leer lässt, wird dieser automatisch mit undefined gefüllt: gemuese = "Spinat"; print(gemuese); Shelly Scripting - Arrays - Hinzufügen von Elementen Index übersprungen 💡 Daher sollte man bei nicht fortlaufender Indexvergabe aufpassen, um unerwartete Lücken im Array zu vermeiden. Ausblick: So geht’s weiter In diesem Beitrag hast du gelernt, wie Arrays aufgebaut sind, wie du auf ihre Elemente zugreifst und wie du sie mit Schleifen durchläufst. Damit hast du die wichtigsten Grundlagen in der Hand, um mit Arrays in Shelly Scripting oder JavaScript allgemein zu arbeiten. Im nächsten Teil zeige ich dir, wie du Arrays aktiv bearbeitest:🔹 Elemente hinzufügen (push, unshift)🔹 Werte entfernen (pop, shift)🔹 Inhalte gezielt ändern oder löschen mit splice() So kannst du deine Daten nicht nur lesen, sondern auch flexibel anpassen – perfekt für dynamische Smarthome-Szenarien. Bleib dran! Read the full article
0 notes
Text
When to Use an Array and When to Use a Linked List in JavaScript
Introduction As a JavaScript developer, you are likely familiar with arrays and linked lists. Both of these data structures have their own advantages and use cases. In this article, we will discuss when to use an array and when to use a linked list in JavaScript, along with example code to demonstrate their usage. When to Use an Array Arrays are one of the most commonly used data structures in…
0 notes
Text
JavaScript’s native Array and Object methods
Think you know JavaScript? Find out how native features can handle Objects and Arrays that simplify coding. No libraries necessary!

0 notes
Text
In JavaScript, you can perform a variety of operations on arrays. Here are some commonly used methods:
The push() method allows you to add one or more elements to the end of an array.
The unshift() method lets you add one or more elements to the beginning of an array.
The filter() method is often used in conjunction with arrow functions to create a new array with all elements that pass the test implemented by the provided function.
#purecode ai company reviews#purecode#purecode company#purecode ai reviews#purecode software reviews#purecode reviews#Javascript#Arrays#Variety Of Operations
0 notes
Text
how to easily create JavaScript arrays and objects containing alphabet letters (a-z) lowercase (A-Z) uppercase and numeric values (0-9).
1 note
·
View note
Text
All About JavaScript Loops
New Post has been published on https://thedigitalinsider.com/all-about-javascript-loops/
All About JavaScript Loops
Every programming language has loops. Loops perform an operation (i.e., a chunk of work) a number of times, usually once for every item in an array or list, or to simply repeat an operation until a certain condition is met.
JavaScript in particular has quite a few different types of loops. I haven’t even used all of them, so for my own curiosity, I thought I’d do a high-level overview of them. And as it turns out, there are pretty good reasons I haven’t used at least a couple of the different types.
So, for now let’s spend a while exploring the different types of loops, what we can do with each of one, and why you might use one over another. (You’ll think that little play on words is absolutely hilarious by the end.)
The while and do...while loops
First up is the while loop. It’s the most basic type of loop and has the potential to be the easiest to read and the fastest in many cases. It’s usually used for doing something until a certain condition is met. It’s also the easiest way to make an infinite loop or a loop that never stops. There is also the do...while statement. Really, the only difference is that the condition is checked at the end versus the beginning of each iteration.
// remove the first item from an array and log it until the array is empty let queue1 = ["a", "b", "c"]; while (queue1.length) let item = queue1.shift(); console.log(item); // same as above but also log when the array is empty let queue2 = []; do let item = queue2.shift() ?? "empty"; console.log(item); while (queue2.length);
The for loop
Next is the for loop. It should be the go to way to do something a certain number of times. If you need to repeat an operation, say, 10 times, then use a for loop instead. This particular loop may be intimidating to those new to programming, but rewriting the same loop in the while-style loop can help illustrate the syntax make it easier to stick in your mind.
// log the numbers 1 to 5 for (let i = 1; i <= 5; i++) console.log(i); // same thing but as a while loop let i = 1; // the first part of a for loop // the second while (i <= 5) console.log(i); i++; // the third ("end");
The for...of and for await...of loops
A for...of loop is the easiest way to loop through an array.
let myList = ["a", "b", "c"]; for (let item of myList) console.log(item);
They aren’t limited to arrays though. Technically they can iterate through anything that implements what is called an iterable protocol. There are a few built-in types that implement the protocol: arrays, maps, set, and string, to mention the most common ones, but you can implement the protocol in your own code. What you’d do is add a [Symbol.iterator] method to any object and that method should return an iterator. It’s a bit confusing, but the gist is that iterables are things with a special method that returns iterators; a factory method for iterators if you will. A special type of function called a generator is a function that returns both a iterable and iterator.
let myList = *[Symbol.iterator]() yield "a"; yield "b"; yield "c"; , ; for (let item of myList) console.log(item);
There is the async version of all the things I just mentioned: async iterables, async iterators, and async generators. You’d use an async iterable with for await...of.
async function delay(ms) return new Promise((resolve) => setTimeout(resolve, ms); ); // this time we're not making an iterable, but a generator async function* aNumberAMinute() let i = 0; while (true) // an infinite loop yield i++; // pause a minute await delay(60_000); // it's a generator, so we need to call it ourselves for await (let i of aNumberAMinute()) console.log(i); // stop after one hour if (i >= 59) break;
One unobvious thing about for await...of statement is that you can use it with non-async iterables and it will work just fine. The reverse, however, is not true; you can’t use async iterables with the for...of statement.
The forEach and map loops
While these are not technically loops per se, you can use them to iterate over a list.
Here is the thing about the forEach method. Historically it was much slower than using a for loop. I think in some cases that may not be true anymore, but if performance is a concern, then I would avoid using it. And now that we have for...of I’m not sure there is much reason to use it. I guess the only reason that it still may come up is if you have a function ready to use as the callback, but you could easily just call that same function from inside the body of for...of.
forEach also receives the index for each item though, so that may be a thing you need too. Ultimately, the decision to use it will probably come down to whether any other code you’re working with uses it, but I personally would avoid using it if I’m writing something new.
let myList = ["a", "b", "c"]; for (let item of myList) console.log(item); // but maybe if I need the index use forEach ["a", "b", "c"].forEach((item, index) => console.log(`$index: $item`); );
Meanwhile, map essentially converts one array into another. It still has the same performance impact that forEach has, but it is a bit nicer to read than the alternative. It’s certainly subjective though, and just like with forEach you’ll want to do what the rest of your other code is doing. You see it a ton in React and React-inspired libraries as the primary way to loop through an array and output a list of items within JSX.
function MyList(items) return ( <ul> items.map((item) => return <li>item</li>; ) </ul> );
The for...in loop
This list of loops in JavaScript wouldn’t be complete without mentioning the for...in statement because it can loop through the fields of an object. It visits fields that are inherited through the object’s prototype chain too, though, and I’ve honestly always avoided it for that reason.
That said, if you have an object literal, then for...in might be a viable way to iterate through the keys of that object. Also it’s worth noting that if you’ve been programming JavaScript for a long time, you may remember that the order of keys use to be inconsistent between browsers, but now the order is consistent. Any key that could be an array index (i.e., positive integers) will be first in ascending order, and then everything else in the order as authored.
let myObject = a: 1, b: 2, c: 3, ; for (let k in myObject) console.log(myObject[k]);
Wrapping up
Loops are something that many programmers use every day, though we may take them for granted and not think about them too much.
But when you step back and look at all of the ways we have to loop through things in JavaScript, it turns out there are several ways to do it. Not only that, but there are significant — if not nuanced — differences between them that can and will influence your approach to scripts.
#ADD#approach#Arrays#Articles#code#curiosity#Delay#generator#generators#impact#it#JavaScript#language#Libraries#list#loop#loops#map#Method#mind#One#Other#performance#Play#programming#Programming Language#prototype#react#Read#REST
0 notes
Text
JavaScript oferece várias funções nativas para manipulação de arrays. Aqui estão algumas das mais comuns e úteis:
1. **`push` e `pop`**:
- `push`: Adiciona um ou mais elementos ao final do array.
- `pop`: Remove o último elemento do array.
```javascript
let arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
arr.pop(); // [1, 2, 3]
```
2. **`shift` e `unshift`**:
- `shift`: Remove o primeiro elemento do array.
- `unshift`: Adiciona um ou mais elementos no início do array.
```javascript
let arr = [1, 2, 3];
arr.shift(); // [2, 3]
arr.unshift(0); // [0, 2, 3]
```
3. **`concat`**:
- Junta dois ou mais arrays.
```javascript
let arr1 = [1, 2];
let arr2 = [3, 4];
let arr3 = arr1.concat(arr2); // [1, 2, 3, 4]
```
4. **`slice`**:
- Retorna uma cópia rasa de uma parte do array, sem modificar o array original.
```javascript
let arr = [1, 2, 3, 4];
let slicedArr = arr.slice(1, 3); // [2, 3]
```
5. **`splice`**:
- Adiciona/remova elementos de qualquer posição do array.
```javascript
let arr = [1, 2, 3, 4];
arr.splice(1, 2); // [1, 4]
arr.splice(1, 0, 2, 3); // [1, 2, 3, 4]
```
6. **`map`**:
- Cria um novo array com os resultados de uma função aplicada a cada elemento do array.
```javascript
let arr = [1, 2, 3];
let mappedArr = arr.map(x => x * 2); // [2, 4, 6]
```
7. **`filter`**:
- Cria um novo array com todos os elementos que passam no teste implementado pela função fornecida.
```javascript
let arr = [1, 2, 3, 4];
let filteredArr = arr.filter(x => x > 2); // [3, 4]
```
8. **`reduce`**:
- Aplica uma função a um acumulador e a cada elemento do array (da esquerda para a direita) para reduzi-lo a um único valor.
```javascript
let arr = [1, 2, 3, 4];
let sum = arr.reduce((acc, x) => acc + x, 0); // 10
```
9. **`find` e `findIndex`**:
- `find`: Retorna o primeiro elemento que satisfaz a função de teste.
- `findIndex`: Retorna o índice do primeiro elemento que satisfaz a função de teste.
```javascript
let arr = [1, 2, 3, 4];
let found = arr.find(x => x > 2); // 3
let foundIndex = arr.findIndex(x => x > 2); // 2
```
10. **`sort`**:
- Ordena os elementos do array e retorna o array.
```javascript
let arr = [4, 2, 3, 1];
arr.sort(); // [1, 2, 3, 4]
```
11. **`forEach`**:
- Executa uma função para cada elemento do array.
```javascript
let arr = [1, 2, 3];
arr.forEach(x => console.log(x)); // 1 2 3
```
Essas são algumas das principais funções de manipulação de array em JavaScript. Elas permitem realizar uma ampla gama de operações para trabalhar com dados de maneira eficiente e concisa.
0 notes
Text
I was too tired to write about it on Friday, but I have to inform everyone, that I've seen a new (for me) way to make ranges in JavaScript:
But why do we need to spread the result of calling Array.prototype.keys() method into an empty array?
It's an iterable, because it has [Symbol.iterator]() method, and it's an iterator, because it has next() method. (Array.prototype.keys() is just one of many methods returning iterable iterators).
But why can't we just use Object.keys() method to achieve the same result, without the need to explicitly transform an iterable iterator into an array? Because Array() constructor (which can be used with or without the new keyword) returns a sparse array, which means it doesn't actually have indexes among its own enumerable properties (!):
In conclusion, while this method of creating ranges with Array.prototype.keys() is more concise and opened my eyes to some subtler differences in how it and similarly named JavaScript methods work (why were they designed in such a way is a separate question), it is obviously only useful if you need a range starting at 0 and increasing with a step of 1. Otherwise you'll need Array.from() method's callback function in order to get the desired kind of range.
#codeblr#javascript#all of this is needlessly complicated#like i don't even mention what array-like objects are#or the fact that Array() constructor works completely differently depending on number of arguments it recieves
3 notes
·
View notes
Text
JavaScript Array Splice Method: A Detailed Exploration
0 notes
Text
Mastering Array Manipulation in JavaScript: A Guide for Amazon Interview
Introduction Arrays are one of the most fundamental data structures in JavaScript, and mastering array manipulation is crucial for any developer. If you are preparing for an Amazon interview, you must have a solid understanding of array operations, as they are commonly asked in technical interviews. In this guide, we will explore the key concepts of array manipulation in JavaScript and provide…
0 notes
Text
PureCode AI review | Working with Arrays and Objects
In JavaScript, arrays and objects serve as structures capable of storing collections. Arrays are ordered lists, whereas objects are key-value pairs. For instance, you could have an array of students’ names or an object representing a student with properties like first name, last name, age, and skills.
#purecode ai company reviews#purecode software reviews#purecode#purecode company#purecode ai reviews#purecode reviews#Arrays And Objects#javascript
0 notes